from datetime import datetime
from extensions import db

class Project(db.Model):
    __tablename__ = 'projects'

    # 基本信息
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    status = db.Column(db.String(20), default='active')  # active/archived

    # App Store Connect 信息
    bundle_id = db.Column(db.String(100), nullable=False, unique=True)
    apple_id = db.Column(db.String(100), nullable=False)
    username = db.Column(db.String(100), nullable=False)
    team_id = db.Column(db.String(100))
    team_name = db.Column(db.String(100))
    
    # API认证信息
    asc_key_id = db.Column(db.String(100))
    asc_issuer_id = db.Column(db.String(100))
    asc_key_file = db.Column(db.String(200))
    
    # Metadata配置
    metadata_path = db.Column(db.String(200))
    primary_category = db.Column(db.String(50))
    secondary_category = db.Column(db.String(50))
    privacy_url = db.Column(db.String(200))
    support_url = db.Column(db.String(200))
    marketing_url = db.Column(db.String(200))
    
    # 发布配置
    automatic_release = db.Column(db.Boolean, default=False)
    phased_release = db.Column(db.Boolean, default=False)

    # 关系
    versions = db.relationship('Version', back_populates='project', lazy='dynamic')

    def __repr__(self):
        return f'<Project {self.name}>'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'bundle_id': self.bundle_id,
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'versions_count': self.versions.count()
        }

    def from_dict(self, data, partial=True):
        """从字典更新项目属性
        
        Args:
            data: 包含项目属性的字典
            partial: 是否允许部分更新。如果为False，所有必填字段都必须存在
        """
        fields = ['name', 'bundle_id', 'apple_id', 'username', 'team_id', 'team_name',
                 'asc_key_id', 'asc_issuer_id', 'asc_key_file', 'metadata_path',
                 'primary_category', 'secondary_category', 'privacy_url', 'support_url',
                 'marketing_url']
        
        required_fields = ['name', 'bundle_id', 'apple_id', 'username'] if not partial else []
        
        # 检查必填字段
        for field in required_fields:
            if field not in data:
                raise ValueError(f'Missing required field: {field}')
        
        # 更新字段
        for field in fields:
            if field in data:
                setattr(self, field, data[field])
        
        # 更新布尔字段
        if 'automatic_release' in data:
            self.automatic_release = bool(data['automatic_release'])
        if 'phased_release' in data:
            self.phased_release = bool(data['phased_release'])
        
        return self
